package com.lagou.config;

//import com.alibaba.druid.pool.DruidDataSource;
import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author <a href="mailto:zhouyong@cqyyt.com">zy</a>
 * @version 1.0
 * @date 2020/12/4 23:11
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream stream) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(stream);
        Element rootElement = document.getRootElement();
        //拿到xml里面任意位置property的值
        List<Element> list = rootElement.selectNodes("//property");
        //用于存储值
        Properties properties = new Properties();
              for (Element element : list) {
            String name = element.attributeValue("name");
             String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
//        //使用druid连接池
//        DruidDataSource dataSource = new DruidDataSource();
//        dataSource.setDriverClassName(properties.getProperty("driverCLass"));
//        dataSource.setUrl(properties.getProperty("jdbcUrl"));
//        dataSource.setUsername();
        //使用c3p0的连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverCLass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);

        //对mapper.xml进行解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String resourse = element.attributeValue("resourse");
            InputStream steam = Resources.getResourceAsSteam(resourse);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(steam);
        }

        return configuration;
    }

}
